package com.kmshack.topscroll;

import ohos.agp.components.*;
import ohos.agp.components.webengine.WebView;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;

public class TopScrollHelper {
    private static TopScrollHelper sInstance;
    private Context mContext;
    private Component mTopView,mBaseView;
    public synchronized static TopScrollHelper getInstance(Context context,Component mTopView) {

        if (sInstance != null) {
            return sInstance;
        }

        sInstance = new TopScrollHelper(context,mTopView);
        return sInstance;
    }
    private TopScrollHelper(Context context,Component mTopView) {
        mContext = context;
        this.mTopView=mTopView;
    }

    private void init() {
        mTopView.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (mBaseView instanceof ListContainer) {
                    if (((ListContainer) mBaseView).getItemProvider() != null && ((ListContainer) mBaseView).getItemProvider().getCount() > 15)
                        ((ListContainer) mBaseView).setSelectedItemIndex(15);
                    mBaseView.scrollTo(0, 0);
                } else if (mBaseView instanceof ScrollView) {
                    ((ScrollView)mBaseView).fluentScrollTo(0,0);
                } else if (mBaseView instanceof WebView) {
                    mBaseView.scrollTo(0, 0);
                } else if(mBaseView instanceof NestedScrollView){
                    ((NestedScrollView)mBaseView).fluentScrollTo(0,0);
                }else {
                    new ToastDialog(mContext).setContentText("暂不支持此控件").show();
                }
            }
        });
        mTopView.setDoubleClickedListener(new Component.DoubleClickedListener() {
            @Override
            public void onDoubleClick(Component component) {
                if (mBaseView instanceof ListContainer) {
                    if (((ListContainer) mBaseView).getItemProvider() != null && ((ListContainer) mBaseView).getItemProvider().getCount() > 15)
                        ((ListContainer) mBaseView).setSelectedItemIndex(15);
                    mBaseView.scrollTo(0, 0);
                } else if (mBaseView instanceof ScrollView) {
                    ((ScrollView)mBaseView).fluentScrollTo(0,0);
                } else if (mBaseView instanceof WebView) {
                    mBaseView.scrollTo(0, 0);
                } else if(mBaseView instanceof NestedScrollView){
                    ((NestedScrollView)mBaseView).fluentScrollTo(0,0);
                }else {
                    new ToastDialog(mContext).setContentText("暂不支持此控件").show();
                }
            }
        });
    }


    public void addTargetScrollView(Component view) {
        if (view == null)
            return;
        mBaseView=view;
        init();
    }
}
